var mySwiper,mySwiper2,mySwiper3,mySwiper4
var btntime = document.getElementById("btntime");
var current_time = document.getElementById('current_time');
var totaltime = document.getElementById('totaltime');
var allPlayTime,num,value,elseStr,sendMessage,newWidth,wsValue
var range = true; //滑动开关
var loo_width = null;  //进度条的宽
var is_baojie = true; //灯光
var is_pause = true; //暂停
var volume = 0.5;  //视频默认音量
var isMessage = false; //是否返回消息
var lockReconnect = false; //避免重复连接
var connectStatus = false; //重连状态
var steTime = null; //清空计时器变量
var countdown_time = 1800; //倒计时时间
var left_btn_arr = [
    {id:1,img:"img/page1/btn1.png",img_h:"img/page1/btn1_h.png"},
    {id:2,img:"img/page1/btn2.png",img_h:"img/page1/btn2_h.png"},
    {id:3,img:"img/page1/btn3.png",img_h:"img/page1/btn3_h.png"},
    {id:4,img:"img/page1/btn4.png",img_h:"img/page1/btn4_h.png"}, 
]
var page2_btn_arr = [
    // = 1 是开 = 0 是关
    // 1-5 虚拟人屏幕     
    {id:1,img:"img/page2/btn_stay.png",img_h:"img/page2/btn_stay_h.png",name:"a-待机循环",order_str:'a_playVideo:0'},
    {id:2,img:"img/page2/btn1.png",img_h:"img/page2/btn1_h.png",name:"a-播放",order_str:'a_play'},
    {id:3,img:"img/page2/btn2.png",img_h:"img/page2/btn2_h.png",name:"a-暂停",order_str:'a_pause'},
    {id:4,img:"img/page2/btn3.png",img_h:"img/page2/btn3_h.png",name:"a-增加音量",order_str:'a_vol'},
    {id:5,img:"img/page2/btn4.png",img_h:"img/page2/btn4_h.png",name:"a-减少音量",order_str:'a_vol'},
    // 6-10智调大屏
    {id:6,img:"img/page2/btn_stay.png",img_h:"img/page2/btn_stay_h.png",name:"b-待机循环",order_str:'b_playVideo:0'},
    {id:7,img:"img/page2/btn1.png",img_h:"img/page2/btn1_h.png",name:"b-播放",order_str:'b_play'},
    {id:8,img:"img/page2/btn2.png",img_h:"img/page2/btn2_h.png",name:"b-暂停",order_str:'b_pause'},
    {id:9,img:"img/page2/btn3.png",img_h:"img/page2/btn3_h.png",name:"b-增加音量",order_str:'b_vol'},
    {id:10,img:"img/page2/btn4.png",img_h:"img/page2/btn4_h.png",name:"b-减少音量",order_str:'b_vol'},
    // 11-15 科普大屏
    {id:11,img:"img/page2/btn_stay.png",img_h:"img/page2/btn_stay_h.png",name:"c-待机循环",order_str:'c_playVideo:0'},
    {id:12,img:"img/page2/btn1.png",img_h:"img/page2/btn1_h.png",name:"c-播放",order_str:'c_play'},
    {id:13,img:"img/page2/btn2.png",img_h:"img/page2/btn2_h.png",name:"c-暂停",order_str:'c_pause'},
    {id:14,img:"img/page2/btn3.png",img_h:"img/page2/btn3_h.png",name:"c-增加音量",order_str:'c_vol'},
    {id:15,img:"img/page2/btn4.png",img_h:"img/page2/btn4_h.png",name:"c-减少音量",order_str:'c_vol'},
    // 16-17 全部灯光 继电器7号口和8号口
    {id:16,img:"img/page2/btn5.png",img_h:"img/page2/btn5_h.png",name:"全部灯光-开",order_str:'#####AT+STACH7=1#AT+STACH8=1'},
    {id:17,img:"img/page2/btn6.png",img_h:"img/page2/btn6_h.png",name:"全部灯光-关",order_str:'#####AT+STACH7=0#AT+STACH8=0'},
    // 18-19 灯膜控制  继电器4号口 
    {id:18,img:"img/page2/btn5.png",img_h:"img/page2/btn5_h.png",name:"灯膜控制-开",order_str:'AT+STACH7=1'},
    {id:19,img:"img/page2/btn6.png",img_h:"img/page2/btn6_h.png",name:"灯膜控制-关",order_str:'AT+STACH7=0'},
    // 20-21筒灯控制 继电器5号口
    {id:20,img:"img/page2/btn5.png",img_h:"img/page2/btn5_h.png",name:"筒灯控制-开",order_str:'AT+STACH8=1'},
    {id:21,img:"img/page2/btn6.png",img_h:"img/page2/btn6_h.png",name:"筒灯控制-关",order_str:'AT+STACH8=0'},
    // 22
    {id:22,img:"img/page2/btn15.png",img_h:"img/page2/btn15_h.png",name:"返回",},

]
var swiper2_length = null, // 待机循环slide的数量
swiper3_length = null, // 智调大屏slide的数量
swiper4_length =null; // 科普大屏slide的数量

function setEvent(){
    settime(countdown_time); //一分钟倒计时	
    isOnline(true) //是否连接服务器 
    swiper_init() 
}

function swiper_init(){
	mySwiper2 = new Swiper ('.swiper2', {
        slidesPerView: 3,
        spaceBetween: 5,
		direction: 'horizontal', // 垂直切换选项
		loop: false, // 循环模式选项
		noSwiping : false,
		observer:true,
		observeParents:true,
		autoHeight: true, 
		// 如果需要前进后退按钮
		navigation: {
			nextEl: '.next2',
			prevEl: '.prev2',
		},
		on:{
			init: function(){
				swiperAnimateCache(this); //隐藏动画元素 
				swiperAnimate(this); //初始化完成开始动画
			}, 
			slideChangeTransitionStart: function(){
				// console.log("slideChangeTransitionStart:"+this.activeIndex);
			},
			slideChangeTransitionEnd: function(){ 
				swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
				//this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); 动画只展现一次，去除ani类名
				console.log("slideChangeTransitionEnd:"+this.activeIndex);
					
			},
		}
	}) 
    mySwiper3 = new Swiper ('.swiper3', {
        slidesPerView: 3,
        spaceBetween: 5,
		direction: 'horizontal', // 垂直切换选项
		loop: false, // 循环模式选项
		noSwiping : false,
		observer:true,
		observeParents:true,
		autoHeight: true, 
		// 如果需要前进后退按钮
		navigation: {
			nextEl: '.next3',
			prevEl: '.prev3',
		},
		on:{
			init: function(){
				swiperAnimateCache(this); //隐藏动画元素 
				swiperAnimate(this); //初始化完成开始动画
			}, 
			slideChangeTransitionStart: function(){
				// console.log("slideChangeTransitionStart:"+this.activeIndex);
			},
			slideChangeTransitionEnd: function(){ 
				swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
				//this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); 动画只展现一次，去除ani类名
				console.log("slideChangeTransitionEnd:"+this.activeIndex);
					
			},
		}
	}) 
    mySwiper4 = new Swiper ('.swiper4', {
        slidesPerView: 3,
        spaceBetween: 5,
		direction: 'horizontal', // 垂直切换选项
		loop: false, // 循环模式选项
		noSwiping : false,
		observer:true,
		observeParents:true,
		autoHeight: true, 
		// 如果需要前进后退按钮
		navigation: {
			nextEl: '.next4',
			prevEl: '.prev4',
		},
		on:{
			init: function(){
				swiperAnimateCache(this); //隐藏动画元素 
				swiperAnimate(this); //初始化完成开始动画
			}, 
			slideChangeTransitionStart: function(){
				// console.log("slideChangeTransitionStart:"+this.activeIndex);
			},
			slideChangeTransitionEnd: function(){ 
				swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
				//this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); 动画只展现一次，去除ani类名
				console.log("slideChangeTransitionEnd:"+this.activeIndex);
					
			},
		}
	})
    //  swiper2_length = mySwiper2.slides.length; 
    //  swiper3_length = mySwiper3.slides.length; 
    //  swiper4_length = mySwiper4.slides.length; 
    swiper2_length = 3; 
    swiper3_length = 3; 
    swiper4_length = 4; 
}


function setData(){
    // 使用示例
    const delayQueue = new DelayQueue();
    $("body").click(function(){
        //点击的时候开始倒计时
        gettime();
    })
    $(".btn1").on('touchend',function(){
        console.log('一键开馆');
        
        delayQueue.tasks = []
        // 添加任务
        delayQueue.tasks.push({ action: () => sendSocket_str('str','#####AT+STACH4=1#AT+STACH5=1') , delay: 1000 });
        delayQueue.tasks.push({ action: () => sendSocket_str('str','#####AT+STACH6=1#AT+STACH7=1') , delay: 1000 });
        delayQueue.tasks.push({ action: () => sendSocket_str('str','#####AT+STACH8=1') , delay: 1000 });
        delayQueue.tasks.push({ action: () => sendSocket_str("str","serialPort-32 06 00 00 00 01 4D C9") , delay: 2000 });

        // 处理任务，按顺序每个任务之间间隔指定的延迟执行
        delayQueue.processTasks();
        
    }) 
    $(".btn2").on('touchend',function(){
        console.log('一键闭馆');
        // const delayQueue = new DelayQueue();
         delayQueue.tasks = []
         delayQueue.tasks.push({ action: () => sendSocket_str('str','#####AT+STACH4=0#AT+STACH5=0') , delay: 1000 });
         delayQueue.tasks.push({ action: () => sendSocket_str('str','#####AT+STACH6=0#AT+STACH7=0') , delay: 1000 });
         delayQueue.tasks.push({ action: () => sendSocket_str('str','#####AT+STACH8=0') , delay: 1000 });
         delayQueue.tasks.push({ action: () => sendSocket_str("str","serialPort-32 06 00 01 00 01 1C 09") , delay: 2000 });
         // 处理任务，按顺序每个任务之间间隔指定的延迟执行
         delayQueue.processTasks();
    }) 
    $(".btn3").on('touchend',function(){
        
        if(is_baojie){
            console.log('保洁模式关闭');
            sendSocket_str('str','####AT+STACH1=0#AT+STACH2=0'); 
            is_baojie = false
        }else{
            console.log('保洁模式开启');
            sendSocket_str('str','####AT+STACH1=1#AT+STACH2=1'); 
            is_baojie = true
        }
    })
    $(".btn4").on('touchend',function(){
        console.log('多媒体控制');
        setTimeout(() => {
            $(".page1, .reconnect_div, .loading_div").hide()
            $(".back_btn").attr("src","img/page2/btn15.png")
            $(".page2").css('visibility','visible')
        }, 200);
        
    })
    $(".back_btn").on('touchend',function(){
        console.log('返回上一页');
        setTimeout(() => {
            $(".page2").css('visibility','hidden')
            $(".reconnect_div, .loading_div").hide()
            $(".page1").fadeIn()
        }, 200);
    })
    $(".jd_click_content").click(function(){
        //点击发送音量
        var clickX = event.offsetX;
        addVloLength(clickX)
        sendSocket_str('num',volume); 
    })
    $(".jd_click_content").bind("touchmove",function(e){
        //移动音量条的位置
        // console.log("touchmove:"+e.originalEvent.changedTouches[0].pageX)
        var clickX = e.originalEvent.changedTouches[0].pageX-125;
        addVloLength(clickX)
    })
    $(".jd_click_content").bind("touchend",function(e){
        //按下结束发送音量
        // console.log("touchmove:"+e.originalEvent.changedTouches[0].pageX)
        var clickX = e.originalEvent.changedTouches[0].pageX-125;
        addVloLength(clickX)
        sendSocket_str('num',volume); 
    })
    // page2_btn_arr id 1-15发送命令
    for(let i = 1; i < page2_btn_arr.length; i++){
        page2_btn_arr.map((item,index)=>{
            let newId = item.id;
            if(newId == i){
                $(".fun_btn" + i).on('touchend',function(){
                    if(i == 4 || i == 9 || i == 14){
                        //增加音量
                        sendSocket_str('num',item.order_str + ':' + vol_change('vol_up',volume)); 
                    }
                    else if(i == 5 || i == 10 || i == 15){
                        //减小音量
                        sendSocket_str('num',item.order_str + ':' + vol_change('vol_down',volume)); 
                    }
                    else{
                        sendSocket_str('str',item.order_str)
                    }
                })
            }
        })

    }


    $(".guanji_div").click(function(){
        clickFun()
    })
    $(".slide").on('touchstart',function(){
        // console.log(2222,"touchstart");
        
        let id = $(this).data("index")
        slide_style_change(id,'slide')
        // $(".btn_stay").attr("src","img/page2/btn_stay.png")
    })
    $(".slide").on('touchend',function(){
        let id = $(this).data("id")
        let slide_type = $(this).data("slide");
        let slide_send_str = '';
        let plat_btn_index = 0;
        if( slide_type == 2 ){
            slide_send_str = "a_playVideo"
            plat_btn_index = 2;
        }
        else if(slide_type == 3){
            //虚拟大屏
            slide_send_str = "b_playVideo"
            plat_btn_index = 7;

        }
        else if(slide_type == 4){
            slide_send_str = "c_playVideo"
            //虚拟大屏
            plat_btn_index = 12;
        }
        sendSocket_str('str',slide_send_str + ":" + id);
        // console.log();
        
        // sendSocket_str('slide_send_str',  id);

        $(".fun_btn" + plat_btn_index).attr("src","img/page2/btn1_h.png")
    })
}

function slide_style_change(e,select = ''){
    // console.log(e,"1111");
    let slide_timeout = 1000;
    let all_slide_length = swiper2_length + swiper3_length + swiper4_length;
    if(select == "slide"){
        //导航按钮切换
        for(let i = 1; i <= all_slide_length; i++){
            if( i == e){
                $(".sc"+ i).attr("src","img/a_play1_h.png")
                setTimeout(() => {
                    //过1s后还原按钮（为了避免a->b发消息但是b->c没有接收到，所以重置按钮状态）
                     $(".sc"+ i).attr("src","img/a_play1.png")
                }, slide_timeout);
            }else{
                $(".sc"+ i).attr("src","img/a_play1.png")
            }
        }
        //导航按钮切换时其余部分按钮样式重置变成可交互状态
        page2_btn_arr.map((item,index)=>{
            let newId = item.id;
            $(".fun_btn" + newId).attr("src",item.img)
            // 将按钮还原为可交互状态
            $(".fun_btn" + newId).removeClass('disabledbutton'); 
        })
    }
    else if(e == 0 && select == ''){
        $(".sd").attr("src","img/a_play1.png")
    }
}

function isOnline(status){
    //是否连接服务器
    if(status == false){
        $(".reconnect_div, .page1, .page3").hide();
        $(".page2").css('visibility','visible')

    }else{
        $(".page2").css('visibility','hidden')
        $(".page1, .page3").hide();
        $(".reconnect_div").show();
        $(".reconnect_div").click(function(){
            console.log('链接服务器');
            wsValue = socketConnect(localUrl);
        })
    } 
}
function playChildClick(e,type,arr){
    // 按钮样式切换
    var id = e;
    let new_arr = []
    if(type == "page1"){
        new_arr = left_btn_arr
    }
    else if(type == "page2"){
        new_arr = page2_btn_arr
    }
    new_arr.map((item,index)=>{
        let newId = item.id
        all_page_btn_style_change(type,newId,id,item)
    })
    slide_style_change(0,'') 
    
    // // touch事件
    // $('.btn1').on('touchstart', function() {
    //     $(this).addClass('nav-active')
    // });
    // // 释放后移除
    // $('.btn1').on('touchend', function() {
    //     $(this).removeClass('nav-active')
    // });
}

function all_page_btn_style_change(page,newId,id,item){
    // page2所有按钮切换样式
    let btn_time = null;
    let btn_name = ''
    // console.log(newId,id,item);
    if(page == 'page1'){
        btn_name = ".btn"
    }
    else if(page == 'page2'){
        btn_name = ".fun_btn"
    }
    if(newId == id){
        $(btn_name + newId).attr("src",item.img_h)
        $(btn_name + newId).addClass('disabledbutton');
            // 模拟长时间运行的操作
            btn_time = setTimeout(function(){
                // 完成操作后，将按钮还原为可交互状态
                $(btn_name + newId).removeClass('disabledbutton');
                $(btn_name + newId).attr("src",item.img) //过1s后还原按钮（为了避免a->b发消息但是b->c没有接收到，所以重置按钮状态）
            }, 1000); // 此处的数字表示操作所需的时间，单位为毫秒
    }else{
        $(btn_name + newId).attr("src",item.img)
        // 将按钮还原为可交互状态
        $(btn_name + newId).removeClass('disabledbutton'); 
    }
}


function removeBtnClass(){
    //返回重置按钮
    
}

function vol_change(type = "",vol){
    vol = parseFloat(vol);
    vol = Math.round(vol * 10) / 10;
    if(type == 'vol_up'){
        vol += 0.1
        volume = vol;
        if(vol > 0.9){
            volume = 1
        }
    }
    else if(type == 'vol_down'){
        vol -= 0.1;
        volume = vol;
        if(vol < 0.1){
            volume = 0
        }
    }
    volume = parseFloat(volume);
    volume = Math.round(volume * 10) / 10;
    console.log(volume,"volume");
    return volume;
}


function addVloLength(coord){
    //进度条宽度显示 音量拖拽 赋值音量
    let clickX = coord;
    loo_width = parseInt( $(".loo").css("width"));
    newWidth = ((clickX/loo_width).toFixed(2))*loo_width;
    volume = (clickX/loo_width).toFixed(2);
    $(".jd_content").css("width", newWidth + 'px')
} 

function clickFun(){
    let timer = null;
    let waitTime = 200; // 该时间间隔内点击才算连续点击（单位：ms）
    let num = 0; // 连续点击次数
    let maxNum = 3; // 最大连续点击次数
    let lastTime = new Date().getTime(); // 上次的点击时间
    document.addEventListener("click", () => {
      let nowTime = new Date().getTime();
      if (nowTime - lastTime < waitTime) {
        num++;
      } else {
        num = 0;
      }
      lastTime = nowTime;
      console.log(num,maxNum);
      if (num >= maxNum) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            if (confirm('您确定要执行要关机吗？')) {
                console.log('用户选择了确认操作')
                sendSocket_str('str','shutdown'); 
              } else {
                console.log('用户选择了取消操作')
              }
        }, 100);
      }
    });
}

function messageReturnFalse(data){
    value = data.type
    num = data.num
    elseStr = data.elseStr
    console.log(elseStr,"elseStr",num,"data.num");
    if(value != "" && isMessage == false){
        isMessage = true;
        reconnect_status_style('success');
        clearInterval(sendMessage)
    }
    if(value == "success"){
        console.log("连接成功");
        videoLength();
        allPlayTime = num;
        volume = elseStr;
        // $("#volumeLabel,#volumeText").text((volume * 100 ).toFixed()+"%");
    }
    else if(value == "volumeChange"){
        volume = num;
        console.log("收到音量了",volume,loo_width);
        $(".jd_content").css("width", volume*loo_width + 'px')
    }
    else if(value == "playTime"){
        videoLengthChange();
    }
}

function settime(countdown) { 
    // 倒计时
    // console.log(countdown);
    if (countdown == 0) { 
        console.log(countdown);
        $(".loading_div").show();
        countdown = countdown_time; 
    }else { 
        $(".loading_div").hide();
        countdown--; 
        steTime = setTimeout(function() {
            settime(countdown) 
        },1000) 
    } 
}

function reconnect_status_style(type = ""){
    $(".button_class").css("color","#fff")
    if(type == "success"){
        // 重连成功页面样式
        $(".reconnect_text").text("连接成功")
        $(".reconnect_div, .reconnect_text").hide();
        $(".page1,.reconnect_text").show();
    }
    else if(type == "failed"){
        // 重连失败页面样式
        $(".reconnect_text").text("自动重连中...")
        $(".reconnect_div, .reconnect_text").show();
        $(".page1,.reconnect_button").hide();
    }
}

function gettime(){
    //页面倒计时
    clearTimeout(steTime) //清空计时器
    settime(countdown_time) //重新倒计时
}

// 创建一个延迟队列,DelayQueue类有一个enqueue方法，它返回一个Promise，在指定的延迟后执行传入的任务。processTasks方法遍历任务队列，并按顺序执行它们，每个任务的执行间有延迟。
class DelayQueue {
    constructor() {
        this.tasks = [];
    }
    enqueue(task, delay) {
      return new Promise((resolve) => {
        setTimeout(() => {
          task();
          resolve();
        }, delay);
      });
    }
    async processTasks() {

      for (let i = 0; i < this.tasks.length; i++) {
        const task = this.tasks[i];
        await this.enqueue(task.action, task.delay);
      }

    }
}
   


  
 
   



